package com.example.web.controller;

import com.example.web.entity.Result;
import com.example.web.entity.User;
import com.example.web.service.UserService;
import com.example.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取用户列表（支持分页和查询）
     */
    @GetMapping
    public Result<Map<String, Object>> getUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            Map<String, Object> result = userService.getUserList(page, size, username);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            User user = userService.findById(id);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }
            user.setPassword(null);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 创建新用户
     */
    @PostMapping
    public Result<User> createUser(@RequestBody User user, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            User createdUser = userService.createUser(user);
            createdUser.setPassword(null);
            return Result.success("用户创建成功", createdUser);
        } catch (Exception e) {
            return Result.error("创建用户失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public Result<User> updateUser(@PathVariable Long id, @RequestBody User user, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            user.setId(id);
            User updatedUser = userService.updateUser(user);
            if (updatedUser == null) {
                return Result.error(404, "用户不存在");
            }
            updatedUser.setPassword(null);
            return Result.success("用户更新成功", updatedUser);
        } catch (Exception e) {
            return Result.error("更新用户失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteUser(@PathVariable Long id, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            boolean deleted = userService.deleteUser(id);
            if (!deleted) {
                return Result.error(404, "用户不存在");
            }
            return Result.success("用户删除成功", null);
        } catch (Exception e) {
            return Result.error("删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户是否已认证
     */
    private boolean isAuthenticated(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return false;
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            return jwtUtils.validateToken(token, username);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从请求中提取Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
    
    /**
     * 获取用户的角色
     */
    @GetMapping("/{userId}/roles")
    public Result<List<Long>> getRolesByUserId(@PathVariable Long userId, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            List<Long> roleIds = userService.getRoleIdsByUserId(userId);
            return Result.success(roleIds);
        } catch (Exception e) {
            return Result.error("获取用户角色失败: " + e.getMessage());
        }
    }
    
    /**
     * 给用户分配角色
     */
    @PostMapping("/{userId}/roles")
    public Result<Boolean> assignRolesToUser(@PathVariable Long userId, @RequestBody List<Long> roleIds, HttpServletRequest request) {
        try {
            if (!isAuthenticated(request)) {
                return Result.error(401, "未认证");
            }
            
            boolean success = userService.assignRolesToUser(userId, roleIds);
            return Result.success("角色分配成功", success);
        } catch (Exception e) {
            return Result.error("分配角色失败: " + e.getMessage());
        }
    }
}